package sany.iec.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sany.iec.config.GlobalVariable;
import sany.iec.entity.ServerEntity;
import sany.iec.enums.ServerType;
import sany.iec.service.UpdateDataService;
import sany.iec.service.WebService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author 托马斯
 * @Date 2025/7/6 19:53
 * @Description DataController
 */
@RestController
@Slf4j
public class DataController {

    @Resource
    private WebService webService;

    @Resource
    private UpdateDataService updateDataService;

    @GetMapping("/data")
    public Object getPointVersion() {
        Map<String, Object> map = new HashMap<>(2);
        map.put("svg_install_default_默认SVG容量", GlobalVariable.SVG_INSTALL_DEFAULT);
        Map<String, Float> treeMap = new TreeMap<>(GlobalVariable.GLOBAL_MAP);
        // 按键升序排序
        map.put("global_data", treeMap);
        return map;
    }

    @GetMapping("/stop")
    public Object stopServer(@RequestParam("port") int port, @RequestParam("flag") int flag) {
        return webService.stopOrStart(port, flag) + "\n1表示开启，其他任意数字均是关闭。";
    }

    @GetMapping("/update")
    public Object updateData(@RequestParam("port") int port, @RequestParam("k") String key, @RequestParam("v") float value) throws InterruptedException {
        AtomicReference<ServerEntity> s = new AtomicReference<>();
        GlobalVariable.SERVER_LIST.forEach(server -> {
            if (server.getPort().equals(port)) {
                s.set(server);
            }
        });
        if(s.get() == null) {
            return "不存在此端口的服务。";
        }
        if (s.get().getServerType().equals(ServerType.MODBUS)) {
            return updateDataService.updateModbusData(s.get(), key, value);
        } else {
            return updateDataService.updateIEC104Data(s.get(), key, value);
        }
    }

}
